package com.carl.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.carl.common.constant.AttrEnum;
import com.carl.common.dto.es.SkuESModel;
import com.carl.mall.product.convert.EntityToVoConvert;
import com.carl.mall.product.dao.AttrAttrgroupRelationDao;
import com.carl.mall.product.dao.AttrGroupDao;
import com.carl.mall.product.entity.AttrAttrgroupRelationEntity;
import com.carl.mall.product.entity.AttrGroupEntity;
import com.carl.mall.product.entity.CategoryEntity;
import com.carl.mall.product.service.AttrAttrgroupRelationService;
import com.carl.mall.product.service.AttrGroupService;
import com.carl.mall.product.service.CategoryService;
import com.carl.mall.product.vo.AttrEntityVO;
import com.carl.mall.product.vo.AttrGroupRelationVO;
import com.carl.mall.product.vo.AttrResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.common.utils.PageUtils;
import com.carl.common.utils.Query;

import com.carl.mall.product.dao.AttrDao;
import com.carl.mall.product.entity.AttrEntity;
import com.carl.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrEntityVO attrEntityVO) {
        AttrEntity attrEntity = EntityToVoConvert.INSTANCE.attrEntityToVO(attrEntityVO);
        //1.保存规格参数的信息
        this.save(attrEntity);
        //2.保存规格参数和属性组的关联关系
        Long attrGroupId = attrEntityVO.getAttrGroupId();
        //查询属性分组中的排序值  穿过来的属性类型为基本属性才会更新到属性属性组关联表中
        if (!StringUtils.isEmpty(attrGroupId) && Objects.equals(attrEntityVO.getAttrType(), AttrEnum.ATTR_TYPE_BASE.getCode())){
            Integer sort = attrGroupService.getById(attrGroupId).getSort();
            if (attrGroupId > 0) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrGroupId(attrGroupId);
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId()); //这个是属性的id 必须从实体entity获取
                attrAttrgroupRelationEntity.setAttrSort(sort); //属性分组中的排序
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }
        }


    }

    @Override
    public PageUtils queryByPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> wrapper= new QueryWrapper<>();

        //为1 查attr_type = 1 否则查attr_type = 0
        wrapper.eq("attr_type","base".equalsIgnoreCase(attrType) ? 1 : 0);

        if (catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }

        String key =(String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(obj -> {
                obj.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this
                .page(
                        new Query<AttrEntity>().getPage(params),
                        wrapper);

        PageUtils pageUtils = new PageUtils(page);
        //关联的我们需要查询出类别名称和属性组的名称
        //List<AttrEntity> list = (List<AttrEntity>) pageUtils.getList();//这么写也没毛病
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVO> collect = records.stream().map((attrEntity) -> {
            AttrResponseVO attrResponseVO = EntityToVoConvert.INSTANCE.attrEntityToResponseVO(attrEntity);
            //设置分类名称
            CategoryEntity entity = categoryService.getById(attrEntity.getCatelogId());
            if (entity != null) {
                attrResponseVO.setCatelogName(entity.getName());
            }
            //如果为基本属性参数,则需要返回属性组名称
            if ("base".equalsIgnoreCase(attrType)) {
                //设置属性组名称
                AttrAttrgroupRelationEntity attrGroupRelation = attrAttrgroupRelationDao
                        .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                //如果attrGroupRelation不为空那就在AttrAttrgroupRelationEntity这个表里查 如果为空就不用查了证明是销售属性 不用给AttrGroupName
                if (!StringUtils.isEmpty(attrGroupRelation)) {
                    String attrGroupName = attrGroupService.getById(attrGroupRelation.getAttrGroupId()).getAttrGroupName();
                    attrResponseVO.setGroupName(attrGroupName);
                }
            }
            return attrResponseVO;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;

    }

    @Override
    public AttrResponseVO queryByAttrId(Long attrId) {
        //找出所属分类和所属分组
        AttrEntity attrEntity = this.getById(attrId);
        AttrResponseVO attrResponseVO = EntityToVoConvert.INSTANCE.attrEntityToResponseVO(attrEntity);
        if (attrEntity.getAttrType().equals(AttrEnum.ATTR_TYPE_BASE.getCode())){
            AttrAttrgroupRelationEntity relationEntity =
                    attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId));
            if (!StringUtils.isEmpty(relationEntity)){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                attrResponseVO.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                if (!StringUtils.isEmpty(attrGroupEntity)) {
                    attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVO.setCatelogPath(catelogPath);
        return attrResponseVO;
    }
    @Transactional
    @Override
    public void updateByEntity(AttrEntityVO attrEntityVO) {
        AttrEntity attrEntity = EntityToVoConvert.INSTANCE.attrEntityToVO(attrEntityVO);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType().equals(AttrEnum.ATTR_TYPE_BASE.getCode())){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntityVO.getAttrId());
            relationEntity.setAttrGroupId(attrEntityVO.getAttrGroupId());
            Integer integer = attrAttrgroupRelationDao
                    .selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrEntityVO.getAttrId()));
            if (integer > 0){
                attrAttrgroupRelationDao
                        .update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntityVO.getAttrId()));
            }else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public void removeByAttrIds(Long[] attrIds) {
        for (Long attrId : attrIds) {
            AttrEntity attrEntity = this.getById(attrId);
            if (attrEntity.getAttrType().equals(AttrEnum.ATTR_TYPE_BASE.getCode())){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrId));
                attrAttrgroupRelationDao
                        .delete(new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
                this.removeById(attrId);
            }
             this.removeById(attrId);
        }
    }

    @Override
    public List<AttrResponseVO> queryByAttrGroupId(Long attrGroupId) {
        List<AttrResponseVO> attrResponseVOS = null;
       if (!StringUtils.isEmpty(attrGroupId)){
           List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao
                   .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
            attrResponseVOS = relationEntities
                   .stream()
                   .filter(Objects::nonNull)
                   .map((e) -> {
                       AttrEntity attrEntity = attrService.getById(e.getAttrId());
                       AttrResponseVO attrResponseVO = EntityToVoConvert.INSTANCE.attrEntityToResponseVO(attrEntity);
                       return attrResponseVO;
                   }).collect(Collectors.toList());
       }
       return attrResponseVOS;

    }

    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> entityList = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());
        //批量删除关联数据
        //attrAttrgroupRelationDao.deleteBatchIds(entityList);
        attrAttrgroupRelationDao.removeByBatchIds(entityList);
    }

    @Override
    public PageUtils queryPageWithTreeNoAttr(Map<String, Object> params, Long attrGroupId) {
        //通过分组id在查出分组表的实体
        AttrGroupEntity groupEntity = attrGroupService.getById(attrGroupId);
        //根据这个分组表的实体查到其分类id
        Long catelogId = groupEntity.getCatelogId();
        //找到这个类别下的所有分组信息
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao
                .selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //获取所有分组的ids
        List<Long> groupIds = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId)
                .collect(Collectors.toList());
        //找出关联表的所有关联实体类的信息
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        //通过这个实体找到分类的id
        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        //构造查询条件 是base的
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",catelogId)
                .eq("attr_type", AttrEnum.ATTR_TYPE_BASE.getCode());
        //如果中间表里没有数据则就是表明还没有关联,只需要在排除上面的attrIds
        if (!attrIds.isEmpty()){
            wrapper.notIn("attr_id",attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), wrapper);

        return new  PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIdList) {
        List<AttrEntity> attrEntities = this.list(new QueryWrapper<AttrEntity>()
                .in("attr_id", attrIdList).eq("search_type", 1));
        return attrEntities.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
    }

}